package cn.com.nes.site.service.app.impl;

import cn.com.nes.common.em.platform.OpeMethodEnum;
import cn.com.nes.common.util.DBUtils;
import cn.com.nes.common.util.HttpUtils;
import cn.com.nes.common.util.ParameterUtil;
import cn.com.nes.common.util.ZipUtils;
import cn.com.nes.mybatis.agent.ope.entity.IsEquipmentFaultHistoryInfo;
import cn.com.nes.mybatis.agent.ope.entity.IsWxsb;
import cn.com.nes.mybatis.agent.ope.mapper.IsAppMapper;
import cn.com.nes.mybatis.agent.ope.mapper.IsDeviceProtocolDataItemInfoMapper;
import cn.com.nes.mybatis.agent.ope.mapper.IsWxsbMapper;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.OtherData;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.module.dao.newmall.NewmallDaoImpl;
import cn.com.nes.site.service.app.AppService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.SqlBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;


@Slf4j
@Service
public class AppServiceImpl implements AppService {
    @Resource
    private NewmallDaoImpl newmallDaoImpl;
    @Resource
    private IsWxsbMapper isWxsbMapper;
    @Resource
    private IsAppMapper isAppMapper;
    @Resource
    private IsDeviceProtocolDataItemInfoMapper dataItemInfoMapper;

    @Override
    public PageData checkVerCodeIncreaseTime(String phone, String vercode) throws SQLException {
        Connection conn = null;
        PageData res = new PageData();
        try {
            conn = DBUtils.getJNDIDBConn();
            res = newmallDaoImpl.checkVerCodeIncreaseTime(phone, vercode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.rollback();
                conn.close();
            }
        }
        return res;
    }

    @Override
    public PageData login(DataReq req) throws SQLException {
        Connection conn = null;
        PageData res = new PageData();
        try {
            conn = DBUtils.getJNDIDBConn();
            res = newmallDaoImpl.login(conn, req);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.rollback();
                conn.close();
            }
        }
        return res;
    }

    @Override
    public PageData queryCommand(DataReq req) {
        //返回值对象

        // 检查入参
        if (ObjectUtil.isNull(req)) {
            return PageData.error("请求参数为空");
        }

        // 检查入参dtuId
        if (StrUtil.isEmpty(ParameterUtil.getString(req, "dtuId"))) {
            return PageData.error("请求参数dtuId为空");
        }
        String dtuId = ParameterUtil.getString(req, "dtuId");
        // 根据DTUID，查询无线设备
        IsWxsb wxsb = isWxsbMapper.selectWxSbInfoByDtuId(dtuId);
        //查询指令
        if (ObjectUtil.isNotNull(wxsb) && !"".equals(wxsb)) {
            List<Map<String, Object>> itemsData = isAppMapper.getProtocolInfoByProtocol(wxsb.getProtocolId());
            if (itemsData.size() > 0) {
                String url = OpeMethodEnum.testQueryCommand.url();
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        sendCommand(itemsData, dtuId, wxsb.getProtocolId(), wxsb.getDtuTypeId(), req.getKey(), url);
                    }
                });
                thread.start();
                return PageData.ok();
            } else {
                return PageData.ok("未查询到设备指令");
            }
        }
        return PageData.ok("未查询到无线设备");

    }

    @Override
    public PageData getMyDevList(DataReq req) {
        String sbId = ParameterUtil.getString(req, "sbId");
        List<Map<String, Object>> data = isAppMapper.getMyDevList(req.getUinfo().getUserId(), sbId);
        if (data.size() == 0 || data == null) {
            return PageData.ok("未查询到无线设备");
        }
        for (int m = 0; m < data.size(); m++) {
            String otherData = (String) data.get(m).get("other_data");
            String protocolId = (String) data.get(m).get("protocol_id");
            if (otherData != null) {
                List<OtherData> parsedOtherData = ZipUtils.processOtherData(otherData);
                if (parsedOtherData != null && parsedOtherData.size() > 0) {
                    for (OtherData datum : parsedOtherData) {
                        judgingData(datum.getF(), datum.getV(), datum.getS(), data.get(m),protocolId);

                    }
                }
            }
        }
        return PageData.ok(data);
    }

    private static void sendCommand(List<Map<String, Object>> list, String dtuId, String protocolId, Long dtuTypeId, String token, String url) {
        HashSet set = new HashSet<>();
        for (int k = 0; k < list.size(); k++) {
            Map<String, Object> map = list.get(k);
            set.add(map.get("commandId"));

        }
        set.forEach(element -> HttpUtils.sendCommand(dtuId, protocolId, dtuTypeId, 0, element.toString(), token, url));
    }

    //参数判断过滤方法  type1为单体2为电池组3为故障信息判断
    public static void judgingData(String key, String value, String V, Map<String, Object> map, String deviceProtocolId) {
        //单体的

            if ("a435".equals(key)) {
                map.put("batteryCapacity",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "batteryCapacity")
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
        key="a438";
        value="343434";
            if ("a438".equals(key)) {
                map.put("currentBatteryLevel",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "currentBatteryLevel")//剩余电量
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            key="a812";
            value="343434";
            if ("a812".equals(key)) {
                map.put("dailyChargingCapacity",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "dailyChargingCapacity")//日充电电量
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
          key="a814";
            value="454545";
            if ("a814".equals(key)) {
                map.put("dailyDischargeCapacity",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "dailyDischargeCapacity")//日放电电量
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            if ("a815".equals(key)) {
                map.put("dailyChargingTime",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "dailyChargingTime")//日充电时长
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            if ("a816".equals(key)) {
                map.put("dailyDischargeTime",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "dailyDischargeTime")//日充电时长
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            if ("a817".equals(key)) {
                map.put("accumulatedChargingCapacity",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "accumulatedChargingCapacity")//累计充电容量
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            if ("a818".equals(key)) {
                map.put("accumulatedChargingCapacity",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "accumulatedChargingEle")//累计充电电量
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            if ("a819".equals(key)) {
                map.put("accumulatedDischargeCapacity",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "accumulatedDischargeCapacity")//累计放电容量
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            if ("a820".equals(key)) {
                map.put("accumulatedDischargeCapacity",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "accumulatedDischargeEle")//累计放电电量
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            if ("a821".equals(key)) {
                map.put("accumulatedChargingTime",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "accumulatedChargingTime")//累计充电时间
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            if ("a824".equals(key)) {
                map.put("accumulatedDischargeTime",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "accumulatedDischargeTime")//累计放电时间
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            if ("a962".equals(key)) {
                map.put("runningState",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "runningState")//BMS运行状态
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
            if("a2402".equals(key)){
                map.put("runningState",MapBuilder.create(new HashMap<String, Object>())
                        .put("f", key)
                        .put("s", value)
                        .put("v", V)
                        .put("n", "faultConditions")//BMS故障状态
                        .put("x",getNameEnglish(key,deviceProtocolId))
                        .map());
            }
        if ("a435".equals(key)) {
            map.put("batteryCapacity", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "batteryCapacity")
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        key = "a438";
        value = "343434";
        if ("a438".equals(key)) {
            map.put("currentBatteryLevel", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "currentBatteryLevel")//剩余电量
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        key = "a812";
        value = "343434";
        if ("a812".equals(key)) {
            map.put("dailyChargingCapacity", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "dailyChargingCapacity")//日充电电量
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        key = "a814";
        value = "454545";
        if ("a814".equals(key)) {
            map.put("dailyDischargeCapacity", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "dailyDischargeCapacity")//日放电电量
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        if ("a815".equals(key)) {
            map.put("dailyChargingTime", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "dailyChargingTime")//日充电时长
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        if ("a816".equals(key)) {
            map.put("dailyDischargeTime", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "dailyDischargeTime")//日充电时长
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        if ("a817".equals(key)) {
            map.put("accumulatedChargingCapacity", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "accumulatedChargingCapacity")//累计充电容量
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        if ("a818".equals(key)) {
            map.put("accumulatedChargingCapacity", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "accumulatedChargingEle")//累计充电电量
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        key = "a819";
        value = "11111";
        if ("a819".equals(key)) {
            map.put("accumulatedDischargeCapacity", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "accumulatedDischargeCapacity")//累计放电容量
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        key = "a820";
        value = "22222";
        if ("a820".equals(key)) {
            map.put("accumulatedDischargeCapacity", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "accumulatedDischargeEle")//累计放电电量
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        if ("a821".equals(key)) {
            map.put("accumulatedChargingTime", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "accumulatedChargingTime")//累计充电时间
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        if ("a824".equals(key)) {
            map.put("accumulatedDischargeTime", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "accumulatedDischargeTime")//累计放电时间
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        if ("a962".equals(key)) {
            map.put("runningState", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "runningState")//BMS运行状态
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        if ("a2402".equals(key)) {
            map.put("runningState", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "faultConditions")//BMS故障状态
                    .put("x", getNameEnglish(key,deviceProtocolId))
                    .map());
        }
        if("a433".equals(key)){
            map.put("SOH", MapBuilder.create(new HashMap<String, Object>())
                    .put("f", key)
                    .put("s", value)
                    .put("v", V)
                    .put("n", "SOH")//BMS故障状态
                    .put("x", "SOH")
                    .map());
        }

          /*  //电池组
        if("a432".equals(key)){ // 电池堆总个数


        }
        if("a433".equals(key)){ // 电池堆在线个数


        }
        if("a434".equals(key)){ // 电池簇总个数


        }
        if("a435".equals(key)){ // 电池簇在线个数


        }
            if ("a407".equals(key)) { //运行模式
                hashMap.put("operatingMode", value);
            }
            if ("a3913".equals(key)) {//运行状态
                hashMap.put("runningState", value);
            }
            if ("a2499".equals(key)) {//储能充电功率
                hashMap.put("energyStorageChargingPower", value);
            }
            if ("a2500".equals(key)) { //储能放电功率
                hashMap.put("energyStorageDischargePower", value);
            }
            if ("a447".equals(key)) {//储能日充电量
                hashMap.put("dailyChargingCapacityOfEnergyStorage", value);
            }
            if ("a448".equals(key)) {//储能月充电量
                hashMap.put("monthlyChargingCapacityForEnergyStorage", value);
            }
            if ("a449".equals(key)) { //储能年充电量
                hashMap.put("annualChargingCapacityOfEnergyStorage", value);
            }
            if ("a451".equals(key)) { //储能日放电量
                hashMap.put("dailyDischargeOfEnergyStorage", value);
            }
            if ("a452".equals(key)) { //储能月放电量
                hashMap.put("monthlyEnergyStorageDischarge", value);
            }
            if ("a453".equals(key)) { //储能年放电量
                hashMap.put("annualDischargeOfEnergyStorage", value);
            }
            if ("a455".equals(key)) {//储能日收益
                hashMap.put("dailyEarningsFromEnergyStorage", value);
            }
            if ("a456".equals(key)) {//储能月收益
                hashMap.put("monthlyIncomeFromEnergyStorage", value);
            }
            if ("a457".equals(key)) {//储能年收益
                hashMap.put("annualRevenueFromEnergyStorage", value);
            }
            if ("a285".equals(key)) {//当前可充电量
                hashMap.put(" currentRechargeableCapacity", value);
            }
            if ("a286".equals(key)) {//当前可放电量
                hashMap.put("currentDischargeCapacity", value);
            }
            if ("a2483".equals(key)) {//MOS温度
                hashMap.put("MOSTemperature", value);
            }
            if ("a2".equals(key)) {//储能累积充电量
                hashMap.put("accumulatedChargingCapacityOfEnergyStorage", value);
            }
            if ("a30".equals(key)) {//储能累积放电量
                hashMap.put("accumulatedDischargeOfEnergyStorage", value);
            }
            if ("a441".equals(key)) {//系统总装机容量
                hashMap.put("totalInstalledCapacityOfTheSystem", value);
            }

*/
    }

    @Override
    public PageData getHistoryData(DataReq req) throws SQLException {
        int total = 0;
        Connection connection = null;
        List<Map<String, Object>> page = new ArrayList<>();
        PageData ok = null;
        Calendar calendar = Calendar.getInstance();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String dtuId = ParameterUtil.getString(req, "dtuId");
        String type = ParameterUtil.getString(req, "type");
        try {
            connection = DBUtils.getJNDIclikchouse();
            // 默认查询一天的数据
            String startTime = "";
            String endTime = "";
            if ("1".equals(type) || "".equals(type)) {
                if (StrUtil.isEmpty(ParameterUtil.getString(req, "day")) || !"".equals(ParameterUtil.getString(req, "day"))) {
                    String day = ParameterUtil.getString(req, "day");
                    startTime = day + " 00:00:00";
                    endTime = day + " 24:00:00";
                } else {
                    startTime = DateUtil.format(new Date(), "yyyy-MM-dd") + " 00:00:00";
                    endTime = DateUtil.format(new Date(), "yyyy-MM-dd") + " 24:00:00";
                }
                ok = PageData.ok(page);
            }
            if ("2".equals(type)) {
                int year = calendar.get(Calendar.YEAR);
                if (StrUtil.isEmpty(ParameterUtil.getString(req, "month")) && !"".equals(ParameterUtil.getString(req, "month"))) {
                    String month = ParameterUtil.getString(req, "month");
                    startTime = year + "-" + month + "-01 00:00:00";
                    endTime = year + "-" + month + "-31 00:00:00";
                } else {
                    int month = calendar.get(Calendar.MONTH) + 1;
                    if (month > 10) {
                        startTime = year + "-" + month + "-01 00:00:00";
                        endTime = year + "-" + month + "-31 00:00:00";
                    } else {
                        startTime = year + "-0" + month + "-01 00:00:00";
                        endTime = year + "-0" + month + "-31 00:00:00";
                    }

                }
                ok = PageData.ok(page);
            }
            if ("3".equals(type)) {
                if (StrUtil.isEmpty(ParameterUtil.getString(req, "year")) && !"".equals(ParameterUtil.getString(req, "year"))) {
                    String year = ParameterUtil.getString(req, "year");
                    startTime = year + "-01-01 00:00:00";
                    endTime = year + "-12-31 24:00:00";
                } else {
                    int year = calendar.get(Calendar.YEAR);
                    startTime = year + "-01-01 00:00:00";
                    endTime = year + "-12-31 24:00:00";
                }
                ok = PageData.ok(page);
            }
            // 获取所有的设备id
            final String sqlForEquipmentIds = SqlBuilder.create()
                    .select("distinct sb_id")
                    .from("is_norm_data_his")
                    .where(" dtu_id = ? and gmt_create >= ? and gmt_create <= ? ")
                    .build();
            ps = connection.prepareStatement(sqlForEquipmentIds, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            ps.setString(1, dtuId);
            ps.setString(2, startTime);
            ps.setString(3, endTime);
            rs = ps.executeQuery();
            List<String> equipmentIds = new ArrayList<>();
            if (rs != null) {
                while (rs.next()) {
                    equipmentIds.add("'" + rs.getString("sb_id") + "'");
                }
                rs.close();
            }
            ps.close();
            if (equipmentIds.size() == 0) {
                return ok;
            }
            String equipmentIdPredicate;
            equipmentIdPredicate = " and sb_id in (" + CollUtil.join(equipmentIds, ",") + ") ";
            String pageSql = "";
            if ("1".equals(type) || "".equals(type)) {
                pageSql = "select sb_id ,gmt_create as gmt_time from is_norm_data_his" +
                        "        where dtu_id = ?" + equipmentIdPredicate + " and gmt_create >= ? and gmt_create < ?" +
                        "order by gmt_create desc ";

            } else {

                pageSql = "select sb_id ,max(gmt_create) as gmt_time from is_norm_data_his" +
                        "        where dtu_id = ?" + equipmentIdPredicate + " and gmt_create >= ? and gmt_create < ?" +
                        "        group by sb_id ,formatDateTime(gmt_create, '%F 00:00')\n" +
                        "order by formatDateTime(gmt_create, '%F 00:00') desc ";
            }
            ps = connection.prepareStatement(pageSql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

            ps.setString(1, dtuId);
            ps.setString(2, startTime);
            ps.setString(3, endTime);
            rs = ps.executeQuery();

            List<String> gmtCreates = new ArrayList<>();
            List<Map<String, Object>> results = new ArrayList<>();
            if (rs != null) {
                while (rs.next()) {
                    gmtCreates.add("'" + rs.getString("gmt_time") + "'");
                }
                rs.close();
            }

            ps.close();
            total = gmtCreates.size();
            String gmtCreate;
            gmtCreate = "formatDateTime(gmt_create, '%Y-%m-%d %R:%S') in (" + CollUtil.join(gmtCreates, ",") + ") ";
            final String sql = "select sb_id, device_protocol_id, other_data, gmt_create from is_norm_data_his  a where " + gmtCreate + equipmentIdPredicate + " order by gmt_create desc ";
            ps = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            rs = ps.executeQuery();
            List<Map<String, Object>> mapResult = new ArrayList<>();
            if (rs != null) {
                while (rs.next()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("deviceProtocolId", rs.getString("device_protocol_id"));
                    map.put("otherData", rs.getString("other_data"));
                    map.put("gmtCreate", rs.getString("gmt_create"));
                    mapResult.add(map);
                }
            }
            for (Map<String, Object> result : mapResult) {
                Map<String, Object> map = new HashMap<>();
                // 转换other data
                final String otherData = result.get("otherData").toString();
                map.put("gmtCreate", result.get("gmtCreate").toString());
                if (otherData != null) {
                    List<OtherData> parsedOtherData = ZipUtils.processOtherData(otherData);
                    if (parsedOtherData != null && parsedOtherData.size() > 0) {
                        for (OtherData datum : parsedOtherData) {
                            judgingData(datum.getF(), datum.getV(), datum.getS(), map, result.get("deviceProtocolId").toString());
                        }
                        page.add(map);
                    }
                }

            }
            if ("3".equals(type)) {
                ArrayList list = new ArrayList();
                list.add("dailyChargingCapacity");
                list.add("dailyDischargeCapacity");
                Map<String, Object> dataMap = SplitData(page, list);
                Map<String, Object> map = maergeMap(page, list);
                page.clear();
                page.add(map);
                ok.setData(dataMap);
            }else {
                ArrayList list = new ArrayList();
                list.add("dailyChargingCapacity");
                list.add("dailyDischargeCapacity");
                Map<String, Object> map = SplitData(page, list);
                ok.setData(map);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (connection != null) {
                connection.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (rs != null) {
                rs.close();
            }
        }
        return ok;
    }

    @Override
    public PageData getFaultRecords(DataReq req) {
        String sbId = ParameterUtil.getString(req, "sbId");
        List<Map<String, Object>> fault = isAppMapper.getFaultRecords(req.getUinfo().getId(), sbId);
        return PageData.ok(fault);
    }

    //多个相同map合并数据
    public static Map<String, Object> maergeMap(List<Map<String, Object>> page, ArrayList list) {
        Map<String, Object> mapAll = new HashMap<String, Object>();
        for (Map<String, Object> map : page) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                for (int k = 0; k < list.size(); k++) {
                    String key = entry.getKey();
                    if (key.equals(list.get(k))) {
                        HashMap hashMap = (HashMap) entry.getValue();
                        HashMap mapAllValue = (HashMap) mapAll.get(entry.getKey());
                        if (mapAllValue == null) {
                            mapAll.put(key, hashMap);
                            hashMap.put("s", Integer.parseInt(hashMap.get("s").toString()));
                        } else {
                            int sum = Integer.parseInt(hashMap.get("s").toString()) + Integer.parseInt(mapAllValue.get("s").toString());
                            mapAll.put(key, hashMap);
                            hashMap.put("s", sum);
                        }
                    }

                }

            }
        }
        return mapAll;
    }

    public static Map<String, Object> SplitData(List<Map<String, Object>> page, ArrayList list) {
        Map<String, Object> mapAll = new HashMap<String, Object>();
        Map<String, Object> map=page.get(1);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                for (int k = 0; k < list.size(); k++) {
                    String key = entry.getKey();
                    if (key.equals(list.get(k))) {
                        mapAll.put(key, entry.getValue());
                    }

                }
            }

        return mapAll;
    }
//查询故障的定时任务实现类
    public void getRealTimeData() {
    /* log.info("定时任务 -> 获取运行数据故障信息，记录入库 -- 开始");
        List<Map<String, Object>> realTimeData = isAppMapper.getRealTimeData("dp_30242512962878088759228502735484861");
        if (realTimeData != null && realTimeData.size() > 0) {
        for (int i=0;i<realTimeData.size();i++){
            HashMap <String, Object> hashMap=new HashMap<>();
            Map<String, Object> map = realTimeData.get(i);
            // 转换other data
            final String otherData = map.get("other_data").toString();
            hashMap.put("sbId",map.get("sb_id").toString());
            hashMap.put("manufactureId",map.get("device_protocol_id").toString());
            if (otherData != null) {
                List<OtherData> parsedOtherData = ZipUtils.processOtherData(otherData);
                if (parsedOtherData != null && parsedOtherData.size() > 0) {
                    for (OtherData datum : parsedOtherData) {
                        if ("a2427".equals(datum.getF()) && "2".equals(datum.getV())) {
                            hashMap.put(datum.getF(),datum.getV());
                            faultJudgingData(hashMap);
                        }
                    }
                }
                }
            }
        }
        log.info("定时任务 -> 获取运行数据故障信息，记录入库 -- 结束");*/
    }





    public  void faultJudgingData(HashMap hashMap) {

     //温差过大
            switch (hashMap.get("a2428").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2428","温差过大一级严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2428","温差过大二级中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2428","温差过大三级轻微故障",hashMap);
                    break;
                default:
                   break;
            }

           //压差过大
            switch (hashMap.get("a2429").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2429","压差过大严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2429","压差过大中级故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2429","压差过大轻微故障",hashMap);
                    break;
                default:
                   break;

        }
   //单体低温
            switch (hashMap.get("a2430").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2430","单体低温严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2430","单体低温中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2430","单体低温轻微故障",hashMap);
                    break;
                default:
                    break;
            }

        //单体过温
            switch (hashMap.get("a2431").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2431","单体过温严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2431","单体过温中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2431","单体过温轻微故障",hashMap);
                    break;
                default:
                break;
            }
       //单体欠压
            switch (hashMap.get("a2432").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2432","单体欠压严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2432","单体欠压中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2432","单体欠压轻微故障",hashMap);
                    break;
                default:
                  break;
            }

       //单体过压
            switch (hashMap.get("a2433").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2433","单体过压严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2433","单体过压中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2433","单体过压轻微故障",hashMap);
                    break;
                default:
                    break;
            }

       //总压过压
            switch (hashMap.get("a2438").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2438","总压过压严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2438","总压过压中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2438","总压过压轻微故障",hashMap);
                    break;
                default:
                    break;
            }

       //绝缘漏电
            switch (hashMap.get("a2439").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2439","绝缘漏电严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2439","绝缘漏电中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2439","绝缘漏电轻微故障",hashMap);
                    break;
                default:
                 break;
            }

     //SOC过低
            switch (hashMap.get("a2440").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2440","SOC过低严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2440","SOC过低中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2440","SOC过低微故障",hashMap);
                    break;
                default:
                    break;
            }
        //SOC过高
            switch (hashMap.get("a2441").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2441","SOC过高严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2441","SOC过高中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2441","SOC过高微故障",hashMap);
                    break;
                default:
                    break;
            }
           //短路保护
            switch (hashMap.get("a2442").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2442","短路保护严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("1","a2442","短路保护中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("1","a2442","短路保护微故障",hashMap);
                    break;
                default:
                    break;
            }
          //MOS温度
            switch (hashMap.get("a2443").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2443","MOS温度严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2443","MOS温度中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2443","MOS温度微故障",hashMap);
                    break;
                default:
                    break;
            }
          //环境温度
            switch (hashMap.get("a2406").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2406","环境温度严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2406","环境温度中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2406","环境温度微故障",hashMap);
                    break;
                default:
                    break;
            }
         //放电过流
            switch (hashMap.get("a3148").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a3148","放电过流严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a3148","放电过流中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a3148","放电过流微故障",hashMap);
                    break;
                default:
                    break;
            }
        //放电过流
            switch (hashMap.get("a2486").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2486","充电过流严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2486","充电过流中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2486","充电过流微故障",hashMap);
                    break;
                default:
                    break;
            }
        //电芯失效
            switch (hashMap.get("a2488").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("3","a2488","电芯失效严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("3","a2488","电芯失效中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2488","电芯失效微故障",hashMap);
                    break;
                default:
                    break;
            }
         //电芯温度
            switch (hashMap.get("a2465").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2465","电芯温度严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("1","a2465","电芯温度中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("1","a2465","电芯温度微故障",hashMap);
                    break;
                default:
                    break;
            }
           //模拟前端状态
            switch (hashMap.get("a2466").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2466","模拟前端状态严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2466","模拟前端状态中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("2","a2466","模拟前端状态微故障",hashMap);
                    break;
                default:
                  break;
            }

           //保险丝状态
            switch (hashMap.get("a2493").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2493","保险丝状态严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("1","a2493","保险丝状态中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("1","a2493","保险丝状态微故障",hashMap);
                    break;
                default:
                    break;
            }
          //供电过低
            switch (hashMap.get("a2494").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2494","供电过低严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("1","a2494","供电过低态中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("1","a2494","供电过低状态微故障",hashMap);
                    break;
                default:
                    break;
            }
           //供电过高
            switch (hashMap.get("a2495").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2495","供电过高严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("1","a2495","供电过高态中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("1","a2495","供电过高状态微故障",hashMap);
                    break;
                default:
                    break;
            }
          //开路
            switch (hashMap.get("a2496").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2496","开路严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("1","a2496","开路中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("1","a2496","开路状态微故障",hashMap);
                    break;
                default:
                 break;
            }

         //粘连
            switch (hashMap.get("a2497").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2497","粘连严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2497","粘连中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("2","a2497","粘连中等故障",hashMap);
                    break;
                default:
                    break;
            }
        //EMS通信异常
            switch (hashMap.get("a2502").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("2","a2502","粘连中等故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("2","a2502","EMS通信异常中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("3","a2502","EMS通信异常中等故障",hashMap);
                    break;
                default:
                    break;
            }
        //温度采集线异常
            switch (hashMap.get("a2503").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2503","温度采集线异常严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("1","a2503","温度采集线异常中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("1","a2503","温度采集线异常微故障",hashMap);
                    break;
                default:
                    break;
            }
        //电压采集线异常
            switch (hashMap.get("a2504").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2504","电压采集线异常严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("1","a2504","电压采集线异常中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("1","a2504","电压采集线异常微故障",hashMap);
                    break;
                default:
                  break;
            }
          //环流
            switch (hashMap.get("a2505").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2505","环流严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("1","a2505","环流中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("1","a2505","环流微故障",hashMap);
                    break;
                default:
                break;
            }
        //自检失败
            switch (hashMap.get("a2506").toString()){
                case "1" :
                    getIsEquipmentFaultHistoryInfo("1","a2506","自检失败严重故障",hashMap);
                    break;
                case "2":
                    getIsEquipmentFaultHistoryInfo("1","a2506","自检失败中等故障",hashMap);
                    break;
                case "3":
                    getIsEquipmentFaultHistoryInfo("1","a2506","自检失败微故障",hashMap);
                    break;
                default:
                    break;
            }
    }


public void  getIsEquipmentFaultHistoryInfo(String faultlevel,String dataItemId,String erroCode,HashMap hashMap){
    IsEquipmentFaultHistoryInfo isEquipmentFaultHistoryInfo=new IsEquipmentFaultHistoryInfo();
   String  faultId="fault_230607721205966"+hashMap.get("sbId").toString();
    isEquipmentFaultHistoryInfo.setFaultId(faultId);
    isEquipmentFaultHistoryInfo.setSbId(hashMap.get("sbId").toString());
    isEquipmentFaultHistoryInfo.setManufactureId(hashMap.get("manufactureId").toString());
    isEquipmentFaultHistoryInfo.setDataItemId(dataItemId);
    isEquipmentFaultHistoryInfo.setAlertTime(new Date());
    isEquipmentFaultHistoryInfo.setState(1);
    isEquipmentFaultHistoryInfo.setFaultSource(0);
    isEquipmentFaultHistoryInfo.setSjly("qgApp");
    isEquipmentFaultHistoryInfo.setDataItemId(dataItemId);
    isEquipmentFaultHistoryInfo.setErroCode(erroCode);
    isEquipmentFaultHistoryInfo.setFaultlevel(faultlevel);
    isEquipmentFaultHistoryInfo.setHandlingmeasures("");
    isAppMapper.addFaultRecords(isEquipmentFaultHistoryInfo);

}

public static String getNameEnglish(String name,String deviceProtocolId ) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    String value="";
    Connection connection = DBUtils.getJNDIclikchouse();
    String pageSql = "select b.name_english as nameEnglish from is_data_item_template_info a inner join is_device_protocol_data_item_info  b on a.template_id=b.template_id where a.field_name=? and b.protocol_id=? limit 1";
    try {
        ps = connection.prepareStatement(pageSql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

    ps.setString(1, "a387"); //name
    ps.setString(2, deviceProtocolId);
    rs = ps.executeQuery();
    List<String> equipmentIds = new ArrayList<>();
    if (rs != null) {
        while (rs.next()) {
            value=rs.getString(1);
        }
        rs.close();
    }
    ps.close();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
        return value;
}

}
